package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.*;
import com.koocloud.electroplatemanage.pojo.*;
import com.koocloud.electroplatemanage.pojo.mainpojo.OrderResource;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.StorageService;
import com.koocloud.electroplatemanage.utils.HexUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.*;

/**
 * @program: electroplatemanage
 * @description: 仓库服务层实现类
 * @author: zww
 * @create: 2020-11-23 10:44
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class StorageServiceImpl implements StorageService {
    @Resource
    private IncomePartJudgeMapper incomePartJudgeMapper;
    @Resource
    private StorageMapper storageMapper;
    @Resource
    private IUserDao iUserDao;
    @Resource
    private MainProductionMapper mainProductionMapper;
    @Resource
    private ProcessCheckMapper processCheckMapper;
    @Resource
    private ProductionTaskMapper productionTaskMapper;

    Lock lock = new ReentrantLock();

    /**
     *@Description:分页查询所有记录
     *@Param: [page, limit, beginTime, endTime, storageVo]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit,String beginTime,String endTime, StorageVo storageVo) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                lock.lock();
                int rows = -1;
                //开始查询在工表，状态为7的插入仓库页面(排产) 并且检验表deleteFlag = 2的即已检验待入库的数据
                List<WIP> wipList= mainProductionMapper.selectAllWIPByLocation(CHECK);
                if(!StringUtils.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {

                            //判断检验表该工单号deleteFlag是否 = 2
                            ProcessCheck processCheck=processCheckMapper.selectByWorkOrderNumber(wip.getWorkOrderNumber());
                            //deleteFlag = 2的即已检验待入库的数据
                            if(!"2".equals(processCheck.getDeleteFlag())) {
                                continue;
                            }
                            //数据库重复工单号校验
                            int count = storageMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }


                            StorageVo insertStorageVo= new StorageVo();

                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置创建人
                                insertStorageVo.setCreator(wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置创建时间
                                insertStorageVo.setCreateTime(wip.getEntryTime());
                            }
                            String workOrderNumber = wip.getWorkOrderNumber();
                            //设置工单号
                            insertStorageVo.setWorkOrderNumber(workOrderNumber);
                            //设置删除标志
                            insertStorageVo.setDeleteFlag("1");
                            ProductionTask productionTask=productionTaskMapper.selectByWorkOrderNumber(workOrderNumber);
                            //根据工单号查询台账表记录
                            IncomePartJudgeVo incomePartJudgeVo = incomePartJudgeMapper.selectByWorkOrderNumber(productionTask.getPlanWorkOrderNumber());





                            if(!StringUtils.isEmpty(incomePartJudgeVo)) {
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getOrderNumber())) {
                                    //设置订单号
                                    insertStorageVo.setOrderNumber(incomePartJudgeVo.getOrderNumber());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartUnitCode())) {
                                    //设置来件单位编码
                                    insertStorageVo.setIncomePartUnitCode(incomePartJudgeVo.getIncomePartUnitCode());
                                }

                                //todo 应该取检验的合格数量
                                /*if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartQuantity())) {
                                    //当前单据数量
                                    insertStorageVo.setCurrentQuantity(incomePartJudgeVo.getIncomePartQuantity());
                                }*/
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDrawNoCode())) {
                                    //设置图号编码
                                    insertStorageVo.setDrawNoCode(incomePartJudgeVo.getDrawNoCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getModelNumber())) {
                                    //设置型号
                                    insertStorageVo.setModelNumber(incomePartJudgeVo.getModelNumber());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getModelType())) {
                                    //设置型别
                                    insertStorageVo.setModelType(incomePartJudgeVo.getModelType());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getPartName())) {
                                    //设置零件名称
                                    insertStorageVo.setPartName(incomePartJudgeVo.getPartName());
                                }
                                rows=storageMapper.insert(insertStorageVo);
                                //记录成功插入条数
                            }

                        }
                    }
                }
                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                    //开始分页
                    PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                    //如果不传就查询当天的
                    if (StringUtils.isEmpty(beginTime)) {
                        beginTime = HexUtil.getCurrentDate();
                    }
                    if (StringUtils.isEmpty(endTime)) {
                        endTime = HexUtil.getCurrentDate();
                    }

                    List<StorageVo> storageVoList = storageMapper.selectAllData(beginTime, endTime, storageVo);
                    //构造分页实体
                    PageInfo<StorageVo> info = new PageInfo<>(storageVoList);
                    if (info.getTotal() > 0) {
                        //查询到数据
                        return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                    } else {
                        //没有查询到数据
                        return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                    }
                }
                else {
                    return ResponseTemplate.builder().code(1).message("在工表数据导入失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }
    /**
     *@Description:新增一条记录
     *@Param: [storageVo, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate insert(StorageVo storageVo,String userId) {
        try {
                lock.lock();
                Date date = new Date();//获取当前的日期
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String strDate = df.format(date);//获取String类型的时间
                storageVo.setCreateTime(strDate);

                //设置创建人
                User user = iUserDao.selectByPk(userId);
                storageVo.setCreator(user.getJobNum());
                storageVo.setDeleteFlag("1");
                //没有异常并且插入数据条数大于0
                int rows = storageMapper.insert(storageVo);
                if (rows > 0) {
                    return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
                } else {//没有异常并且插入数据失败，原则上不出现
                    return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
                }

        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //出现异常返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description:逻辑删除一条记录
     *@Param: [workOrderNumber, deleteFlag]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate delete(String workOrderNumber,String deleteFlag) {
        try {
            lock.lock();
            int row = 0;
                    //判断删除操作是否成功
                    row = storageMapper.delete(workOrderNumber,deleteFlag);
                    if (row > 0) {
                        //删除成功返回数据
                        return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
                    }
                    else {
                        //删除失败返回提示
                        return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
                    }

        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }
    /**
     *@Description:修改一条记录
     *@Param: [storageVo, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate update(StorageVo storageVo,String userId) {
        try {

                    lock.lock();
                    //设置创建人
                    User user = iUserDao.selectByPk(userId);
                    storageVo.setModifier(user.getJobNum());
                    //没有异常并且修改数据条数大于0
                    int rows = storageMapper.update(storageVo);
                    if(rows>0) {
                        return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
                    }
                    else {//没有异常并且修改数据失败，原则上不出现
                        return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
                    }

        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }
    /**
     *@Description:入库确认
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate confirmEntryInfo(String workOrderNumber,String userId) {
        try{
            lock.lock();
            //操作人
            User user = iUserDao.selectByPk(userId);
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //改变检验状态
            processCheckMapper.changeState(workOrderNumber);
            /*//工单号表
            WorkOrder workOrder = mainProductionMapper.selectWorkOrderByPk(workOrderNumber);
            workOrder.setCurrentLocation(PROCESSPREPARATION);
            int limit = mainProductionMapper.updateWorkOrder(workOrder);*/
            //生产在工表
            WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
            wip.setCurrentLocation(WAREHOUSING);
            int rows =  mainProductionMapper.updateWIP(wip);
            //生产实际表
            String postion = CHECK;
            List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
            int row = 0;
            if(!StringUtils.isEmpty(orderResourceList.get(0))) {
                OrderResource orderResource = orderResourceList.get(0);
                //上一状态完成时间
                orderResource.setCompletionTime(strDate);
                //上一状态完成人
                orderResource.setCompletedPerson(user.getJobNum());
                mainProductionMapper.updateOrderResource(orderResource);
                orderResource.setRoutePosition(WAREHOUSING);
                //投入时间
                orderResource.setEntryTime(strDate);
                //投入人
                orderResource.setEntryPerson(user.getJobNum());
                //上一状态完成时间
                orderResource.setCompletionTime(null);
                //上一状态完成人
                orderResource.setCompletedPerson(null);
                row = mainProductionMapper.insertOrderResource(orderResource);

            }
            if(rows>0 && row >0) {
                return ResponseTemplate.builder().code(0).message("确认成功").count(1l).build();
            } else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("确认失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description:申请发货
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate applyDeliverGoods(String workOrderNumber,String userId) {
        try{
            lock.lock();
            //操作人
            User user = iUserDao.selectByPk(userId);
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //改变入库状态
            storageMapper.changeState(workOrderNumber);
            /*//工单号表
            WorkOrder workOrder = mainProductionMapper.selectWorkOrderByPk(workOrderNumber);
            workOrder.setCurrentLocation(PROCESSPREPARATION);
            int limit = mainProductionMapper.updateWorkOrder(workOrder);*/
            //生产在工表
            WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
            wip.setCurrentLocation(DELIVERGOODS);
            int rows =  mainProductionMapper.updateWIP(wip);
            //生产实际表
            String postion = WAREHOUSING;
            List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
            int row = 0;
            if(!StringUtils.isEmpty(orderResourceList.get(0))) {
                OrderResource orderResource = orderResourceList.get(0);
                //上一状态完成时间
                orderResource.setCompletionTime(strDate);
                //上一状态完成人
                orderResource.setCompletedPerson(user.getJobNum());
                mainProductionMapper.updateOrderResource(orderResource);
                orderResource.setRoutePosition(DELIVERGOODS);
                //投入时间
                orderResource.setEntryTime(strDate);
                //投入人
                orderResource.setEntryPerson(user.getJobNum());
                //上一状态完成时间
                orderResource.setCompletionTime(null);
                //上一状态完成人
                orderResource.setCompletedPerson(null);
                row = mainProductionMapper.insertOrderResource(orderResource);

            }
            if(rows>0 && row >0) {
                return ResponseTemplate.builder().code(0).message("申请发货成功").count(1l).build();
            } else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("申请发货失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }
}
